package com.wzl.backend.controller;

import com.wzl.backend.common.ResponseCode;
import com.wzl.backend.common.Result;
import com.wzl.backend.pojo.User;
import com.wzl.backend.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "用户接口")
@CrossOrigin("*")
public class UserController {

    @Autowired
    UserService userService;

    @ApiOperation("登录")
    @PostMapping("login")
    public Result login(String username , String password) {
        User user;
        try {
            user = userService.login(username , password);
        } catch (RuntimeException e) {
            return Result.fail(e.getMessage() , ResponseCode.BAD_REQUEST);
        }
        return Result.ok(user);
    }

    @ApiOperation("通过id获取用户")
    @GetMapping("{id}")
    public Result getUserById(@PathVariable Long id) {
        User byId = userService.getById(id);
        return Result.ok(byId);
    }

    @ApiOperation("获取所有用户全部信息")
    @GetMapping("getAll")
    public Result getAll() {
        List<User> list = userService.list();
        return Result.ok(list);
    }

    @ApiOperation("修改用户信息")
    @PostMapping("update")
    public Result update(User user) {
        System.out.println(user);
        boolean update = userService.updateById(user);
        if (update) {
            return Result.ok();
        } else {
            return Result.fail("修改失败" , ResponseCode.BAD_REQUEST);
        }
    }

    @ApiOperation("通过id删除用户")
    @DeleteMapping("delete/{id}")
    public Result delete(@PathVariable Long id) {
        boolean remove = userService.removeById(id);
        if (remove) {
            return Result.ok();
        } else {
            return Result.fail("用户id不存在" , ResponseCode.BAD_REQUEST);
        }
    }

    @ApiOperation("添加新用户")
    @PostMapping("add")
    public Result add( User user) throws InterruptedException {
        Thread.sleep(1000L);
        boolean save = userService.addUser(user);
        if (save) {
            return Result.ok();
        } else {
            return Result.fail("邮箱已被使用，请直接登录", ResponseCode.BAD_REQUEST);
        }
    }

    @ApiOperation("获取用户头像")
    @GetMapping("avatar/{id}")
    public Result avatar(@PathVariable Long id) {
        try {
            return Result.ok(userService.getAvatar(id));
        }catch (Exception e) {
            return Result.fail(ResponseCode.BAD_REQUEST);
        }
    }

    @ApiOperation("上传头像")
    @PostMapping("uploadAvatar")
    public Result updateAvatar(Long id , String file) {
        System.out.println("上传头像 : " + id);
        boolean b = userService.updateAvatar(id ,file);
        return Result.ok(b);
    }
}
